package com.bicycle.common.helper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;

import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

public class JedisClusterHelper {
	private static Logger LOGGER = LoggerFactory.getLogger(JedisClusterHelper.class);

	private JedisCluster jedisCluster;

	public void setJedisCluster(JedisCluster jedisCluster) {
		this.jedisCluster = jedisCluster;
	}

	/**
	 * get获取数据
	 * 
	 * @param key
	 * @return {@link String}
	 */
	public String get(String key) {
		try {
			return jedisCluster.get(key);
		} catch (Exception e) {
			LOGGER.error("JedisClusterHelper get method error:", e);
		}
		return null;
	}

	/**
	 * set获取数据
	 *
	 * @param key
	 * @param value
	 * @return {@link String}
	 */
	public String set(String key, String value) {
		try {
			return jedisCluster.set(key, value);
		} catch (Exception e) {
			LOGGER.error("JedisClusterHelper set method error:", e);
		}
		return null;
	}

	/**
	 * 判断key是否存在
	 * 
	 * @param key
	 * @return
	 * @see
	 */
	public boolean exists(String key) {
		try {
			return jedisCluster.exists(key);
		} catch (Exception e) {
			LOGGER.error("JedisClusterHelper exists method error:", e);
			return false;
		}
	}

	/**
	 * 设置key过期时间
	 * 
	 * @param key
	 * @param expire
	 * @see
	 */
	public long expire(String key, int expire) {
		try {
			return jedisCluster.expire(key, expire);
		} catch (Exception e) {
			LOGGER.error("JedisClusterHelper expire method error:", e);
			return 0;
		}
	}

	/**
	 * 获取相似的key<br/>
	 * bs_* 则会获取到bs_1、bs_2<br/>
	 *
	 * @param keys
	 * @return
	 * @see
	 */
	public Set<String> keys(String keys) {
		try {
			TreeSet<String> keySet = new TreeSet<>();
			Map<String, JedisPool> clusterNodes = jedisCluster.getClusterNodes();
			for (String key : clusterNodes.keySet()) {
				JedisPool jedisPool = clusterNodes.get(key);
				Jedis jedisConn = jedisPool.getResource();
				try {
					keySet.addAll(jedisConn.keys(keys));
				} catch (Exception e) {
					LOGGER.error("Getting keys error: {}", e);
				} finally {
					LOGGER.debug("Jedis connection closed");
					jedisConn.close();
				}
			}
			return keySet;
		} catch (Exception e) {
			LOGGER.error("JedisClusterHelper keys method error:", e);
			return null;
		}
	}

	/**
	 * 删除key
	 * 
	 * @param key
	 * @param expire
	 * @see
	 */
	public long del(String key) {
		try {
			return jedisCluster.del(key);
		} catch (Exception e) {
			LOGGER.error("JedisClusterHelper del method error:", e);
			return 0;
		}
	}

	/**
	 * 自增key方法
	 * 
	 * @param key
	 * @return
	 * @see
	 */
	public long incr(String key) {
		try {
			return jedisCluster.incr(key);
		} catch (Exception e) {
			LOGGER.error("JedisClusterHelper del method error:", e);
			return 0;
		}
	}
}
